import axios from 'axios';
import {Message, Loading} from 'element-ui';
export function post(url, data) {
  axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  let config = {
    url: url,
    //请求方法同上
    method: 'post',
    //请求头信息
    headers: {'X-Requested-With': 'XMLHttpRequest'},
    //parameter参数
    params: data,
    //post参数,如果没有额外的也必须要用一个空对象，否则会报错
    data: data,
    //设置超时时间
    timeout: 5000,
    //返回数据类型
    responseType: 'json',
    withCredentials: true
  }
  var loadingInstance = Loading.service({fullscreen: true, text: "加载中"});
  return axios.post(url, data, config).then(status)
    .then(function (resp) {
      loadingInstance.close();
      return resp.data;
    }).catch((error) => {
      loadingInstance.close();
      Message.error({
        showClose: true,
        message: '服务器异常'
      })
      console.warn('请求出错', error)
    });
}

function status(response) {
  if (response.status >= 200 && response.status < 300) {
    return Promise.resolve(response)
  } else {
    return Promise.reject(new Error(response.statusText))
  }
}

export function get(url, data) {
  var loadingInstance = Loading.service({fullscreen: true, text: "加载中"});

  var instance = axios.create({
    timeout: 5000,
    baseURL: '',
  });
  return instance.get(url, {
    params: data
  }).then(status)
    .then(function (resp) {
      loadingInstance.close();
      return resp.data;
    }).catch((error) => {
      loadingInstance.close();
      Message.error({
        showClose: true,
        message: '服务器异常'
      })
      console.warn('请求出错', error)
    });
}
